// api.js 或 request.js

import  baseURL from "@/request/confing.js"

const request = (options) => {
	const {
		url,
		method = 'GET',
		data = {},
		header = {},
		...other
	} = options;
	// 默认请求头
	const defaultHeaders = {
		'Content-Type': 'application/json'
		// 你可以在这里添加其他默认的请求头
	};
	const value = uni.getStorageSync('token');
	if (value) {
		defaultHeaders.token = `${value}`
	}

	// 合并请求头
	const headers = {
		...defaultHeaders,
		...header
	};

	return new Promise((resolve, reject) => {
		uni.request({
			url: baseURL + url, // 拼接完整的URL
			method,
			data,
			header: headers,
			...other,
			success: (res) => {
				const {
					code,
					data,
					message
				} = res.data;
				if (code === 0) {
					resolve(data);
				} else {
				const msg=typeof message.message==="object"?message.message[0]:message
					uni.showToast({
						title:msg,
						icon: 'none',
						duration: 2000
					});
					reject(new Error(`请求失败，状态码：${msg}`));
				}
			},
			fail: (err) => {
				uni.showToast({
					title: '网络错误，请稍后重试',
					icon: 'none',
					duration: 2000
				});
				reject(err);
			}
		});
	});
};

// 导出封装好的request方法
export default request;